<template>
  <div class="reviews-page">
    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="bg-white dark:bg-gray-900 rounded-xl shadow-sm">
        <!-- 导航栏容器 -->
        <div class="px-6 pt-6">
          <!-- 小标签 -->
          <div
            class="text-sm text-gray-900 dark:text-gray-100 font-medium mb-4"
          >
            我的评价
          </div>

          <!-- 评价类型标签页 -->
          <el-tabs v-model="activeTab" class="reviews-tabs">
            <el-tab-pane label="景点评价" name="spots">
              <template #label>
                景点评价
                <el-badge
                  v-if="reviewCounts.spots"
                  :value="reviewCounts.spots"
                  class="ml-2"
                />
              </template>
            </el-tab-pane>
            <el-tab-pane label="商品评价" name="products">
              <template #label>
                商品评价
                <el-badge
                  v-if="reviewCounts.products"
                  :value="reviewCounts.products"
                  class="ml-2"
                />
              </template>
            </el-tab-pane>
            <el-tab-pane label="酒店评价" name="hotels">
              <template #label>
                酒店评价
                <el-badge
                  v-if="reviewCounts.hotels"
                  :value="reviewCounts.hotels"
                  class="ml-2"
                />
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 评价列表 -->
        <div class="reviews-list px-6">
          <div
            v-for="review in reviewsList"
            :key="review.id"
            class="review-card"
          >
            <!-- 评价头部 -->
            <div class="review-header">
              <div class="review-target">
                <el-image
                  :src="review.targetImage"
                  :alt="review.targetName"
                  class="target-image"
                />
                <div class="target-info">
                  <h3 class="target-name">{{ review.targetName }}</h3>
                  <p class="target-meta">{{ review.targetMeta }}</p>
                </div>
              </div>
              <div class="review-status">
                <el-tag
                  :type="review.status === 'published' ? 'success' : 'info'"
                >
                  {{ review.status === "published" ? "已发布" : "待审核" }}
                </el-tag>
              </div>
            </div>

            <!-- 评价内容 -->
            <div class="review-content">
              <div class="rating-row">
                <el-rate
                  v-model="review.rating"
                  disabled
                  :max="5"
                  allow-half
                  :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                  :void-icon="Star"
                  :void-color="'rgba(128,128,128,0.4)'"
                  show-score
                  :decimal-place="1"
                />
                <span class="review-time">{{
                  formatDate(review.createTime)
                }}</span>
              </div>
              <p class="review-text">{{ review.content }}</p>
              <div v-if="review.images?.length" class="review-images">
                <el-image
                  v-for="(image, index) in review.images"
                  :key="index"
                  :src="image"
                  :preview-src-list="review.images"
                  class="review-image"
                  fit="cover"
                />
              </div>
            </div>

            <!-- 商家回复 -->
            <div v-if="review.reply" class="merchant-reply">
              <div class="reply-header">商家回复：</div>
              <p class="reply-content">{{ review.reply }}</p>
              <div class="reply-time">{{ formatDate(review.replyTime) }}</div>
            </div>

            <!-- 评价操作 -->
            <div class="review-actions">
              <el-button type="primary" text @click="handleEdit(review)">
                编辑
              </el-button>
              <el-button type="danger" text @click="handleDelete(review)">
                删除
              </el-button>
            </div>
          </div>

          <!-- 空状态 -->
          <el-empty v-if="!reviewsList.length" :description="getEmptyText()">
            <el-button type="primary" @click="handleViewTarget">
              {{ getEmptyButtonText() }}
            </el-button>
          </el-empty>
        </div>

        <!-- 分页 -->
        <div v-if="reviewsList.length" class="pagination">
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 编辑评价对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑评价"
      width="600px"
      class="edit-dialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="editForm.rating" show-score allow-half />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评价内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="editForm.images"
            action="/api/upload"
            list-type="picture-card"
            :limit="9"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Star } from "@element-plus/icons-vue";

const router = useRouter();
const activeTab = ref("spots");
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const editDialogVisible = ref(false);
const currentReview = ref(null);

// 评价数量统计
const reviewCounts = ref({
  spots: 0,
  products: 0,
  hotels: 0,
});

// 编辑表单
const editForm = ref({
  rating: 5,
  content: "",
  images: [],
});

// 表单校验规则
const editRules = {
  rating: [{ required: true, message: "请选择评分", trigger: "change" }],
  content: [
    { required: true, message: "请输入评价内容", trigger: "blur" },
    { min: 10, message: "评价内容不能少于10个字符", trigger: "blur" },
  ],
};

// 评价列表数据
const reviewsList = ref([
  {
    id: 1,
    targetType: "spot",
    targetName: "贵港江滨公园",
    targetImage: "/images/spots/spot1.jpg",
    targetMeta: "2024-03-18 游玩",
    rating: 4.5,
    content:
      "环境优美，空气清新，是一个非常适合休闲散步的好去处。江边的景色很漂亮，特别是傍晚时分，夕阳映照在江面上，非常美丽。",
    images: ["/images/reviews/review1-1.jpg", "/images/reviews/review1-2.jpg"],
    status: "published",
    createTime: "2024-03-18 18:30:00",
    reply: "感谢您的好评！我们会继续努力提供更好的服务。",
    replyTime: "2024-03-19 09:00:00",
  },
  // 更多评价数据...
]);

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

// 获取空状态文本
const getEmptyText = () => {
  const textMap = {
    spots: "暂无景点评价",
    products: "暂无商品评价",
    hotels: "暂无酒店评价",
  };
  return textMap[activeTab.value];
};

// 获取空状态按钮文本
const getEmptyButtonText = () => {
  const textMap = {
    spots: "去逛逛景点",
    products: "去逛逛商城",
    hotels: "去看看酒店",
  };
  return textMap[activeTab.value];
};

// 获取评价列表
const getReviews = async () => {
  try {
    // TODO: 调用获取评价列表API
    // const { data } = await api.getReviews({
    //   type: activeTab.value,
    //   page: page.value,
    //   pageSize: pageSize.value
    // });
    // reviewsList.value = data.list;
    // total.value = data.total;
    // reviewCounts.value = data.counts;
  } catch (error) {
    console.error("获取评价列表失败:", error);
    ElMessage.error("获取评价列表失败");
  }
};

// 处理编辑评价
const handleEdit = (review) => {
  currentReview.value = review;
  editForm.value = {
    rating: review.rating,
    content: review.content,
    images: review.images?.map((url) => ({ url })) || [],
  };
  editDialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  if (!currentReview.value) return;

  try {
    // TODO: 调用更新评价API
    // await api.updateReview({
    //   id: currentReview.value.id,
    //   ...editForm.value
    // });

    ElMessage.success("评价已更新");
    editDialogVisible.value = false;
    getReviews();
  } catch (error) {
    console.error("更新评价失败:", error);
    ElMessage.error("更新评价失败");
  }
};

// 处理删除评价
const handleDelete = async (review) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这条评价吗？删除后无法恢复。",
      "删除评价",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // TODO: 调用删除评价API
    // await api.deleteReview(review.id);

    ElMessage.success("评价已删除");
    getReviews();
  } catch (error) {
    if (error === "cancel") return;
    console.error("删除评价失败:", error);
    ElMessage.error("删除评价失败");
  }
};

// 查看目标详情
const handleViewTarget = () => {
  const routeMap = {
    spots: "/spots",
    products: "/shop",
    hotels: "/hotel",
  };
  router.push(routeMap[activeTab.value]);
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  page.value = 1;
  getReviews();
};

// 处理页码变化
const handleCurrentChange = (current) => {
  page.value = current;
  getReviews();
};

// 监听标签页变化
watch(activeTab, () => {
  page.value = 1;
  getReviews();
});

// 页面加载时获取数据
onMounted(() => {
  getReviews();
});
</script>

<style lang="scss" scoped>
.reviews-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-300;

  .reviews-tabs {
    :deep(.el-tabs__header) {
      @apply mb-6;
      border-bottom: 1px solid var(--el-border-color-light);

      .el-tabs__nav-wrap::after {
        @apply bg-transparent;
      }

      .el-tabs__item {
        @apply text-gray-600 dark:text-gray-400 transition-colors duration-300;

        .el-badge__content {
          @apply transform scale-90 origin-top-right;
        }

        &.is-active {
          @apply text-primary-600 dark:text-primary-400;
        }

        &:hover:not(.is-active) {
          @apply text-primary-500 dark:text-primary-300;
        }
      }
    }
  }

  .reviews-list {
    @apply space-y-6;

    .review-card {
      @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md;

      .review-header {
        @apply p-4 flex items-center justify-between border-b border-gray-100 dark:border-gray-700;

        .review-target {
          @apply flex items-center space-x-4;

          .target-image {
            @apply w-16 h-16 rounded-lg object-cover;
          }

          .target-info {
            .target-name {
              @apply text-lg font-medium text-gray-900 dark:text-white;
            }

            .target-meta {
              @apply text-sm text-gray-500 dark:text-gray-400 mt-1;
            }
          }
        }
      }

      .review-content {
        @apply p-4;

        .rating-row {
          @apply flex items-center justify-between mb-3;

          .review-time {
            @apply text-sm text-gray-500 dark:text-gray-400;
          }
        }

        .review-text {
          @apply text-gray-700 dark:text-gray-300 leading-relaxed;
        }

        .review-images {
          @apply grid grid-cols-3 gap-2 mt-4;

          .review-image {
            @apply w-full h-24 rounded-lg object-cover cursor-pointer transition-transform duration-300;

            &:hover {
              @apply transform scale-105;
            }
          }
        }
      }

      .merchant-reply {
        @apply p-4 bg-gray-50 dark:bg-gray-700;

        .reply-header {
          @apply text-sm font-medium text-gray-700 dark:text-gray-300 mb-2;
        }

        .reply-content {
          @apply text-gray-600 dark:text-gray-400;
        }

        .reply-time {
          @apply text-sm text-gray-500 dark:text-gray-500 mt-2;
        }
      }

      .review-actions {
        @apply p-4 bg-gray-50 dark:bg-gray-700 border-t border-gray-100 dark:border-gray-600 flex items-center justify-end space-x-2;

        .el-button {
          @apply transition-all duration-300;

          &:hover {
            @apply transform scale-105;
          }
        }
      }
    }
  }

  .pagination {
    @apply mt-8 flex justify-center pb-6;

    :deep(.el-pagination) {
      @apply bg-white dark:bg-gray-800 p-4 rounded-lg shadow transition-colors duration-300;

      .el-pagination__total {
        @apply text-gray-600 dark:text-gray-400;
      }

      .el-pagination__jump {
        @apply text-gray-600 dark:text-gray-400;
      }

      .el-input__inner {
        @apply bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600;
      }

      button {
        @apply bg-transparent border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400;

        &:disabled {
          @apply bg-gray-100 dark:bg-gray-800 text-gray-400 dark:text-gray-600;
        }

        &:hover:not(:disabled) {
          @apply bg-gray-100 dark:bg-gray-700 text-primary-600 dark:text-primary-400;
        }
      }

      .el-pager li {
        @apply bg-transparent border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400;

        &.active {
          @apply bg-primary-500 dark:bg-primary-600 text-white border-primary-500 dark:border-primary-600;
        }

        &:hover:not(.active) {
          @apply bg-gray-100 dark:bg-gray-700 text-primary-600 dark:text-primary-400;
        }
      }
    }
  }
}

// 添加评价卡片动画
.review-card {
  animation: slideIn 0.5s ease-out forwards;
  opacity: 0;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 为每个评价添加延迟动画
@for $i from 1 through 10 {
  .review-card:nth-child(#{$i}) {
    animation-delay: #{$i * 0.1}s;
  }
}

// 添加空状态动画
.el-empty {
  animation: fadeIn 0.3s ease-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
